# -*- coding: utf-8 -*-
# @Time    : 2018/2/5 上午9:43
# @Author  : Azrael.Bai
# @File    : yinzhou_data_out.py

import datetime
import sys
import time

import pymongo

sys.path.append('../..')
# 日志模块
from logger import Logger

log = Logger('yinzhou_big_detail.log').get_logger()


def get_deviation_time(plus=0):
    time_str = (datetime.datetime.now() + datetime.timedelta(days=plus)).strftime('%Y-%m-%d')
    return time_str


# 定义mongo链接方法
def get_mongo_client(target_db):
    try:
        conn = pymongo.MongoClient(host=target_db["host"],
                                   port=target_db["port"],
                                   serverSelectionTimeoutMS=60)
        conn[target_db['vname']].authenticate(target_db['username'], target_db['password'])
        database = conn[target_db['name']]
        return database
    except Exception as e:
        log.error("mongodb连接错误:")
        log.exception(e)
        time.sleep(1)


# 要查询的mongo库文件配置
MONGO_APP_DATA_CONF = {
    'host': '172.16.215.16',
    'port': 40042,
    'vname': 'app_data',
    'name': 'app_data',
    'username': 'work',
    'password': 'haizhi',
}

# 要查询的表名
COLLECTION_NAME = 'bid_detail'

# 获取查询库
app_data_db = get_mongo_client(MONGO_APP_DATA_CONF)
# 查询语句
# 对查询结果进行分析
money = "bid_money"  # "bid_budget"


def parse_money(item):
    try:
        mv = item.get(money, '0')
        if mv == '' or mv is None:
            mv = "0"
        mv = mv.split(',')[0]
        money_value = eval(mv)
        return money_value
    except:
        pass
    return 0.0


def zhaobiao_all():
    log.info("开始计算招标全部数据...")
    cursor1 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '浙江宁波', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "招标"},
        no_cursor_timeout=True)
    cursor2 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '宁波市', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "招标"},
        no_cursor_timeout=True)
    log.info(cursor1.count())
    log.info(cursor2.count())

    for item in cursor1:
        app_data_db.get_collection('zhejiang_ningbo_zhaobiao_all').save(item)
    for item in cursor2:
        app_data_db.get_collection('zhejiang_ningbo_zhaobiao_all').save(item)

    log.info("招标全部输出完成")


def zhaobiao_more1000w():
    log.info("开始计算招标1000W以上数据...")
    cursor1 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '浙江宁波', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "招标"},
        no_cursor_timeout=True)
    cursor2 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '宁波市', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "招标"},
        no_cursor_timeout=True)
    log.info(cursor1.count())
    log.info(cursor2.count())

    for item in cursor1:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 10000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhaobiao_1000w').save(item)
    for item in cursor2:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 10000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhaobiao_1000w').save(item)
    log.info("招标>1000w输出完成")


def zhongbiao_more500w():
    log.info("开始计算中标500W以上数据...")
    cursor1 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '浙江宁波', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "中标"},
        no_cursor_timeout=True)
    cursor2 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '宁波市', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "中标"},
        no_cursor_timeout=True)
    log.info(cursor1.count())
    log.info(cursor2.count())

    for item in cursor1:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 5000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhongbiao_500w').save(item)
    for item in cursor2:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 5000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhongbiao_500w').save(item)
    log.info("中标>500w输出完成")


def zhongbiao_more1000w():
    log.info("开始计算中标1000W以上数据...")
    cursor1 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '浙江宁波', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "中标"},
        no_cursor_timeout=True)
    cursor2 = app_data_db.get_collection(COLLECTION_NAME).find(
        {"province": "浙江", "city": '宁波市', "publish_time": {"$gte": get_deviation_time(-30)}, "bid_type": "中标"},
        no_cursor_timeout=True)
    log.info(cursor1.count())
    log.info(cursor2.count())

    for item in cursor1:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 5000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhongbiao_1000w').save(item)
    for item in cursor2:
        money_value = parse_money(item)
        if isinstance(money_value, float) or isinstance(money_value, int):
            if money_value >= 5000000.0:
                app_data_db.get_collection('zhejiang_ningbo_zhongbiao_1000w').save(item)
    log.info("中标>1000w输出完成")


if __name__ == '__main__':
    zhaobiao_all()
    zhaobiao_more1000w()
    zhongbiao_more500w()
    zhongbiao_more1000w()
